package cs5226.batchjob;

import javax.servlet.*;
import javax.servlet.http.*;
 
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

public class ScheduleLoader extends HttpServlet
	{
		private static final long serialVersionUID = 1L;
		public static final String DEFAULT_QUARTZ_CONFIG_FILE = "/WEB-INF/classes/quartz.properties";
	    static Log logger = LogFactory.getLog(ScheduleLoader.class);	

	    public void init(ServletConfig config) throws ServletException
	    {	    	   
	        try
	        {
		        super.init(config);
	            scheduleCronJob();           
	        }
	        catch(Exception exception)
	        {
	            logger.error("Failed to load the entire ScheduleLoader.", exception);
	            throw new ServletException(exception);
	        }
	    }
	    
	    private final void scheduleCronJob() throws ServletException {
	        try
	        {			

	            String CRON_RUN_STATUS = getServletConfig().getInitParameter("RUN_CRON_JOB"); 
	            String QUARTZ_CONFIG_FILE = getServletConfig().getInitParameter("QUARTZ_CONFIG_FILE");
	            if("true".equalsIgnoreCase(CRON_RUN_STATUS)){

	            	System.out.println ("============ IT IS SO WRONG ==========");
	            	
                    String CRON_JOB_TIME = "10 * * * * ?"; 
                    if(QUARTZ_CONFIG_FILE == null)
                        QUARTZ_CONFIG_FILE = DEFAULT_QUARTZ_CONFIG_FILE;                   
                    StdSchedulerFactory stdschedulerfactory = new StdSchedulerFactory();                     
                    stdschedulerfactory.initialize(getServletConfig().getServletContext().getResourceAsStream(QUARTZ_CONFIG_FILE));                    
                    Scheduler scheduler = stdschedulerfactory.getScheduler();                     
                    scheduler.start();
                    JobDetail jobdetail = new JobDetail("New Cron Job", "New Cron Job executer",_mthclass$("cs5226.batchjob.CronJob"));
                    jobdetail.getJobDataMap().put("getServletConfig", getServletConfig());
                    
                    
                    logger.info ("Get currently executing job");
                    System.out.println (scheduler.getCurrentlyExecutingJobs());
                    scheduler.unscheduleJob("New Cron Job", "New Cron Job executer");
                    
                    CronTrigger crontrigger = new CronTrigger("New Cron Job", "New Cron Job executer");
                    crontrigger.setCronExpression(CRON_JOB_TIME);
                    scheduler.scheduleJob(jobdetail, crontrigger);
                    
                  
                    
                    System.out.println(scheduler.getJobListenerNames());
                    logger.info("Successfully scheduled the cron job.");
              
	            }
	        }
	        catch(Exception exception)
	        {
	            logger.error("Failed to schedule the cron job.. ", exception);
	            throw new ServletException(exception);
	        }
	    }
	    
	    @SuppressWarnings("rawtypes")
		static Class _mthclass$(String s)
	    {
	        try
	        {
	            return Class.forName(s);
	        }
	        catch(ClassNotFoundException classnotfoundexception)
	        {
	            throw new NoClassDefFoundError(classnotfoundexception.getMessage());
	        }
	    }    
	    public String getServletInfo()
	    {
	        return "ScheduleLoader";
	    }
	    
}
